from rest_framework.filters import BaseFilterBackend
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
from collections import OrderedDict


class MinBaseFilterBackend(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        min_id = request.query_params.get('min_id')
        if min_id:
            return queryset.filter(id__lt=min_id).order_by('-id')
        return queryset


class MaxBaseFilterBackend(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        max_id = request.query_params.get('max_id')
        if max_id:
            # 大于第一次获取的id数据(即新值)
            return queryset.filter(id__gt=max_id).order_by('id')
        return queryset


class OrderBaseFilterBackend(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        bool = request.query_params.get('order')
        mid = request.query_params.get('mid')
        if not bool == 'true':
            # 大于第一次获取的id数据(即新值)
            if mid == "undefined":
                return queryset

            return queryset.filter(id__gt=mid).order_by('id')
        if mid == "undefined":
            return queryset.order_by('-id')

        return queryset.filter(id__lt=mid).order_by('-id')


class SocialListLimitOffsetPagination(LimitOffsetPagination):
    default_limit = 4
    limit_query_param = 'limit'
    offset_query_param = 'offset'
    max_limit = 50

    # 从哪个位置取(重写为0)
    def get_offset(self, request):
        return 0

    def get_paginated_response(self, data):
        next_data = "上拉加载更多"
        if not self.get_next_link():
            next_data = "没有更多了"
        return Response(OrderedDict([
            ('loadmore', next_data),
            ('results', data)
        ]))
